/* ---------------------ECFBOX v1.2.2----------------------- */
/* --> VISIT WWW.NORTHERNMICHIGANBANKRUPTCY.COM/ECFBOX <-- */

function getNotices() {
  //---Change these variables as needed
  //
  //---This label will be used to grab e-mails to process 
  var INBOX_LABEL = "ECFBox";
  //---This is the label used to mark processed e-mails
  var OUTBOX_LABEL = "ECF";
  //---Make this true to received e-mails with attached PDF's; otherwise, false
  var EMAIL_PDFS = true;
  //---If true, a copy of the PDF(s) will be placed in Google Docs.
  var GDOCS = true;
  //---If true, dates detected in ECF Notices will be placed on the Google Calendar below.
  var AUTO_CALENDAR = true;
  //---The Calendar which events will be put on
  var CALENDAR_NAME = "ECFBox";
 
/*
MIT License; Copyright (c) <2012> <Wm Paul Slough (paul@sloughlaw.com)>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
associated documentation files (the "Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions 
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
IN THE SOFTWARE.
*/
  
 
  //---The regex's
  var PDFPage = new RegExp(/iframe.+src="(.+?)"/im);
  var OldLandingPage = new RegExp(/href=['"]([0-9a-zA-Z:\\\/\.]+?)['"]\s?onClick="goDLS\('(.+?)'\D+(\d+?)\D+(\d+?)\D+(\d+?)['"].+?<TD><\/TD><TD>(.+?)<\/TD>/gm);
  var LandingPage = new RegExp(/href=['"](.+?)['"]+?.+?<TD><\/TD><TD>(.+?)<\/TD>/gm);
  var CaseNumber = new RegExp(/Case Number:[\s\S]+?href=.+?>(.+?)(?=<\/[aA]>)/im);
  var CaseName = new RegExp(/Case Name:[\s\S]+?<td>(.+?)(?=<\/td>)/im);
  var DocNumber = new RegExp(/Document Number:[\s\S]+?href=.+?>(.+?)(?=<\/[aA]>)/im);
  var ClaimNumber = new RegExp(/Claim Number:[\s\S]+?href=.+?>(.+?)(?=<\/[aA]>)/im);  
  var DocketText = new RegExp(/Docket Text:([\S\s]+?)(?=<\/p>)/im);
  
  var ilabel = getLabel(INBOX_LABEL);
  var olabel = getLabel(OUTBOX_LABEL);
  
  var threads = ilabel.getThreads();

  for (var i in threads) {
    var messages = threads[i].getMessages();
    for (var j in messages) {
      var message = messages[j];
      var subject = message.getSubject();
      var body = message.getBody();
      var d = message.getDate();
      var date = d.getMonth()+1 + "/" + d.getDate() + "/" + d.getFullYear();
      var userEmail = Session.getUser().getEmail();
      var link = getNoticeLink(body);
      var file_name = subject + " on " + date;
      
      var pdf_links = [];
      var pdfs = [];
      
      try {
        if (link[0] == 2) {
          //--- Direct Link (BNC Doc)
          var data = UrlFetchApp.fetch(link[1]).getContent();
          
          // TODO: code to test if form is available
          
          pdfs.push({fileName:file_name+".pdf", mimeType:"application/pdf" , content:data});
          
        } else {
          
          //--- ECF Notice or Claim
          var page_data = UrlFetchApp.fetch(link[1]);
          var page = page_data.getContentText();
          
          //---Stuff we need for GDocs
          if (link[0] == 0) {
            var doc_no = DocNumber.exec(body)[1].trim();
          } else {
            var doc_no = ClaimNumber.exec(body)[1].trim();
          }
          var case_no = cleanString(CaseNumber.exec(body)[1].trim());
          var case_name = cleanString(CaseName.exec(body)[1].trim());        
          var folder_name = case_no + " | " + case_name;
          
          //--- Check if there are attachments
          
          if (PDFPage.test(page)) {
           
            // TODO: code to test if form is available
            
            //--- No Attachments        
            var pdf_link = cleanString(link[2] + PDFPage.exec(page)[1])
                var data = UrlFetchApp.fetch(pdf_link).getContent();
            pdfs.push({fileName:"["+doc_no+"] "+file_name + ".pdf", mimeType:"application/pdf" , content:data});
            
          } else {
            
            //--- Attachments   
            var l = null; 
            var pdf_page = null;
            while (l = LandingPage.exec(page)) {       
              pdf_page = UrlFetchApp.fetch(link[2]+l[1]).getContentText();

              // TODO: code to test if form is available
              
              if (PDFPage.test(pdf_page)) {
                var pdf_link = cleanString(link[2] + PDFPage.exec(pdf_page)[1])
                    var data = UrlFetchApp.fetch(pdf_link).getContent();
                pdfs.push({fileName:"["+doc_no+"] "+file_name+" ("+l[2]+").pdf", mimeType:"application/pdf" , content:data});
              }
            }
            // -- keep compatibility with prior versions of CM/ECF
            while (l = OldLandingPage.exec(page)) {       
              pdf_page = UrlFetchApp.fetch(l[1]+"?magic_num="+l[5]+"&de_seq_num="+l[4]+"&caseid="+l[3]).getContentText();
              if (PDFPage.test(pdf_page)) {
                var pdf_link = cleanString(link[2] + PDFPage.exec(pdf_page)[1])
                var data = UrlFetchApp.fetch(pdf_link).getContent();
                pdfs.push({fileName:"["+doc_no+"] "+file_name+" ("+l[6]+").pdf", mimeType:"application/pdf" , content:data});
              }
            }            
          }      
        }
        
        //---Send E-Mail
        if (pdfs.length > 0 && EMAIL_PDFS == true) {
          
          message.forward(userEmail, {attachments:pdfs});
        }
        
        //---Google Docs (no BNC notices)
        if (pdfs.length > 0 && GDOCS == true && link[0] != 2) {
          //---Create GDocs folders
          var ecf_folder = getFolder(INBOX_LABEL, null);
          var sub_folder = getFolder(folder_name, ecf_folder);
          var attachments_folder = null;
          
          if (pdfs.length > 1) {
            //---Create a folder for attachments if necessary
            var attachments_folder = getFolder(doc_no + " " + subject, sub_folder);
          }
          
          for(var j in pdfs) {
            var blob = Utilities.newBlob(pdfs[j].content, "application/pdf",pdfs[j].fileName);               
            
            if (attachments_folder == null) {
              //---Just 1 PDF; put in case folder
              sub_folder.createFile(blob);
              
            } else {
              //---More than 1 PDF; use a sub-folder
              attachments_folder.createFile(blob);       
          
            }
          }
        }
            
      } catch(err) {
        //log err
      }
    }
    //---Calendar Dates (no BNC notices or POC's)
    try {
      var docket_txt = cleanString(DocketText.exec(body)[1].trim());
      if (AUTO_CALENDAR == true && link[0] == 0) {
        var dates = findDates(docket_txt);        
        var calendar = getCalendar(CALENDAR_NAME);
        for(var y in dates) {
          var event = calendar.createEventFromDescription(cleanString(dates[y]));          
          event.setDescription("["+doc_no+"] "+file_name+"\n"+docket_txt);
          event.setTitle(event.getTitle() + " ["+case_name+"]");
        }
      }      
    } catch(err) {
      //log cal err
    } finally {    
      // All done!
      message.getThread().removeLabel(ilabel);    
      message.getThread().addLabel(olabel);
    }
  }
}

function getFolder(name, parent) {
  
  try {
    var folder = DocsList.getFolder(name);
  } 
  catch(err) {
    if (parent == null) {
      var folder = DocsList.createFolder(name);
    } else {
      var folder = parent.createFolder(name);
    }
  }  
  return folder;
}
    
function getCalendar(name) {

  var cal = CalendarApp.getCalendarsByName(name)[0];
  
  if (cal == null) {
    var cal = CalendarApp.createCalendar(name);
    cal.setTimeZone(CalendarApp.getDefaultCalendar().getTimeZone());
  }
  return cal;
}
    
function getNoticeLink(body) {
      
  var ECFDoc = new RegExp(/Document Number:[\s\S]+?<a href=.*?['"](http.+?)['"]/im);
  var ClaimDoc = new RegExp(/Claim Number:[\s\S]+?<a href=.*?['"](http.+?)['"]/im);
  var BNCDoc = new RegExp(/To retrieve the notice,[\s\S]+?<a href=.*?['"](.+?.pdf)['"]/im);
  var LinkHost = new RegExp(/(.+?)\/[doc1|?TXT]/im);
  
  var types = [ECFDoc,ClaimDoc,BNCDoc];
  
  for (var x in types) {
    var l = null;
    if (types[x].test(body)){
      l = cleanString(types[x].exec(body)[1])
      return [x, l, LinkHost.exec(l)[1]];
    }
  }
}


function findDates(body) {
  var FindDates = new RegExp(/\.?([^<>\.()]+?\d\d?\/\d\d?\/\d\d\d?\d?[^<>]+?)[\.<\/(]/igm);
  var dates = [];
  var d = null;
  while(d = FindDates.exec(body)){
    dates.push(d[1].trim());
  }  
  return dates;
}

function cleanString(s) {
  s = s.replace(/\&amp;/g,'&');
  s = s.replace(/\&lt;/g,'<');
  s = s.replace(/&#([^\s]*);/g, function(match, match2) {return String.fromCharCode(Number(match2));})
  s = s.replace(/<.*?>/g, '');
  return unescape(s);
}

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};

function getLabel(label) {

  var l = GmailApp.getUserLabelByName(label);
  if(l == null) {
    return GmailApp.createLabel(label);
  } else {
    return l;
  }   
}
